package upicgame.cart.dao.impl;

import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import upicgame.cart.dao.CartItemDao;
import upicgame.entity.CartItem;
import upicgame.entity.Game;
import upicgame.entity.User;
@Repository
public class CartItemDaoImpl implements CartItemDao{
	@Autowired
	private SessionFactory factory;
	public Session getSession() {
		return factory.getCurrentSession();
	}
	@Override
	public List<CartItem> findCartItemById(Integer cartid) {
		String hql = "from CartItem c where c.cart.id=?";
		List<CartItem> list = getSession().createQuery(hql).setParameter(0, cartid).getResultList();
		return list;
	}
	@Override
	public CartItem checkCartItem(Integer cartid,Integer gid) {
		String hql = "from CartItem c where c.cart.id=? and c.game.id=?";
		CartItem item = (CartItem) getSession().createQuery(hql).setParameter(0, cartid).setParameter(1, gid).uniqueResult();
		return item;
	}
	
	@Override
	public void saveCartItem(CartItem item) {
		this.getSession().save(item);
	}

	@Override
	public int delCartItem(Integer id) {
		String hql = "delete from CartItem where id=?";
		int result = getSession().createQuery(hql).setParameter(0, id).executeUpdate();
		return result;

	}
	
	@Override
	public User findUserById(Integer id) {
		User user = getSession().load(User.class, id);
		return user;
	}
	
	public void saveUser(User user) {
		getSession().saveOrUpdate(user);
		
	}
	
	@Override
	public Game findGameById(Integer gid) {
		Game game = (Game) getSession().createQuery("select new Game(id,name,price,discountprice,img,tag,description,platform,developer) from Game where id=?")
				.setParameter(0, gid).uniqueResult();
		return game;
	}

}
